package com.itzg.fileutil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.bind.JAXB;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

public class DirTreeFillerMain {

	@Option(name = "--base", required = true)
	private File baseDir;

	@Option(name = "--scenario", required = false)
	private File scenarioFile;

	public DirTreeFillerMain(File rootDir) {
		super();
		this.baseDir = rootDir;
	}

	protected DirTreeFillerMain() {
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		new DirTreeFillerMain().doMain(args).fill();
	}

	private DirTreeFillerMain doMain(String[] args) {
		CmdLineParser cmdLineParser = new CmdLineParser(this);
		try {
			cmdLineParser.parseArgument(args);
		} catch (CmdLineException e) {
			System.err.println(e.getMessage());
			cmdLineParser.printUsage(System.err);
			System.exit(1);
		}
		return this;
	}

	public void fill() throws IOException {
		checkBaseDir(baseDir);

		Scenario scenario = null;
		if (scenarioFile != null) {
			scenario = JAXB.unmarshal(scenarioFile, Scenario.class);
		} else {
			InputStream defaultsIn = DirTreeFillerMain.class.getClassLoader()
					.getResourceAsStream("fileutil/defaults.xml");
			try {
				scenario = JAXB.unmarshal(defaultsIn, Scenario.class);
			} finally {
				defaultsIn.close();
			}
		}
		
		new DirTreeFiller(baseDir, scenario).fill();
	}

	protected void checkBaseDir(File dir) throws IOException {
		if (dir.isFile()) {
			throw new IOException("Directory " + dir
					+ " is a file that already exists");
		}
		if (dir.isDirectory()) {
			File[] content = dir.listFiles();
			for (File file : content) {
				if (!file.isHidden()) {
					throw new IOException("Directory " + dir
							+ " exists and is not empty");
				}
			}
		} else {
			if (!dir.mkdir()) {
				throw new IOException(
						"Unable to create requested base directory " + dir);
			}
		}
	}

	public File getBaseDir() {
		return baseDir;
	}

	public void setBaseDir(File baseDir) {
		this.baseDir = baseDir;
	}

	public File getScenarioFile() {
		return scenarioFile;
	}

	public void setScenarioFile(File scenario) {
		this.scenarioFile = scenario;
	}

}
